package com.zhiyume.api.util;

import com.zhiyume.exception.AesException;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import net.sf.json.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WXPublicUtils {

    private static final Logger logger = LoggerFactory.getLogger(WXPublicUtils.class);


    /**
     * 验证Token
     * @param msgSignature 签名串，对应URL参数的signature
     * @param timeStamp 时间戳，对应URL参数的timestamp
     * @param nonce 随机串，对应URL参数的nonce
     *
     * @return 是否为安全签名
     * @throws AesException 执行失败，请查看该异常的错误码和具体的错误信息
     */
    public static boolean verifyUrl(String msgSignature, String timeStamp, String nonce)
            throws AesException {
        // 这里的 WXPublicConstants.TOKEN 填写你自己设置的Token就可以了
        String signature = SHAUtils.getSHA1(TypeConstants.WXConstants.WEIXIN_TOKEN, timeStamp, nonce);
        if (!signature.equals(msgSignature)) {
            throw new AesException(AesException.ValidateSignatureError);
        }
        return true;
    }

    public static JSONObject getToken() {
        try {
            // 返回的是string 类型，json
            if (!StringUtil.isBlank(TypeConstants.WXConstants.WX_APPID) &&
                    !StringUtil.isBlank(TypeConstants.WXConstants.WX_APPSECRET)) {

                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
                        +"&appid="+TypeConstants.WXConstants.WX_APPID+"&secret="+TypeConstants.WXConstants.WX_APPSECRET;

                logger.error("url:【"+url+"】");

                String tokenInfo = getResponseString(url);

                logger.error("tokenInfo:【"+tokenInfo+"】");
                return JSONObject.fromObject(tokenInfo);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    public static JSONObject getJsApiTicket(String access_token){
        // 如果是企业号用以下 URL 获取 ticket
        // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
        try{
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="+access_token;
            String jsapi = getResponseString(url);
            return JSONObject.fromObject(jsapi);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    private static String getResponseString(String url) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();


        return response.body().string();
    }

    public static Map config(){

        Map<String,String> result = new HashMap<String,String>();

        return result;
    }
}